function WidgetQuestion(){
    this.allAnswers=[];
    this.question=null;
    this.prevQuestion=null;
    this.nextQuestion =null;
    this.chart=null;
    this.store={};
    this.renderTo="";
    this.html = "";
    this.qhtml = "";
    this.rendered = false;
    this.selectedAnswer=null;
    this.selectedAnswerId=null;
    this.winExplication = null;

    this.get = function(options){
        var _this = this;
        if(options.validateSelected){
            if(_this.selectedAnswerId==null){
                Ext.MessageBox.show({
                    title: 'Error en la operaci\u00F3n',
                    msg: "Debe seleccionar una opción antes de continuar",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.ERROR,
                    minWidth:300
                });
                return;
            }    
        }
        var putHit = true;
        if(this.prevQuestion)   putHit = false;

        var q = this.question;
        Ext.Ajax.request({
            url: BASE_URL + 'questions/'+options.operation,
            method: 'POST',
            params: {
                qCurrentId: q.id, 
                elem_test_id:q.elem_test_id,
                answerId:_this.selectedAnswerId,
                putHit:putHit
            },
            success:function(action) {   
                var res = Ext.decode(action.responseText);
                if(res.success){
                    if(options.onSuccess){
                        options.onSuccess(res);
                    }
                    else{
                        _this.selectedAnswerId = null;
                        $("#"+_this.renderTo+" .exec_question").show(
                            "slide", 
                            {direction: options.effectDirection}, 
                            700, 
                            function(){
                                _this.question = res.data;
                                _this.addAnswers(_this.question.answers);

                                //solo si se usa prev guardamos
                                if(options.effectDirection == 'left'){
                                    _this.nextQuestion = null;
                                    if(res.selected.id)
                                        _this.prevQuestion = res.selected;
                                }
                                else{
                                    if(options.effectDirection == 'right'){
                                        _this.prevQuestion = null;
                                        if(res.selected.id)
                                            _this.nextQuestion = res.selected;
                                    }   
                                }

                                _this.render();
                            }
                        );
                    }
                }
                else{
                    Ext.MessageBox.show({
                        title: 'Error en la operaci\u00F3n',
                        msg: res.message,
                        buttons: Ext.MessageBox.OK,
                        icon: Ext.MessageBox.ERROR,
                        minWidth:250,
                        minHeight:200
                    });
                }
            },
            failure:function(form, action) {     
                if(action.failureType == 'load'){                            
                    Ext.Msg.alert('Error', action.result.reason);
                } 
                else{
                    Ext.Msg.alert('Alerta!', 'Servidor no encontrado: ' + action.response.responseText); 
                } 
            }
        });
    }
    //lamada ajax de siguiente pregunta
    this.next = function(){
        var validate = true;
        if(this.prevQuestion)   validate = false;
        this.get({operation:'next',effectDirection:'right', validateSelected:validate});
    }
    //lamada ajax de  pregunta anterior
    this.prev = function(_object){
        var _this = this;
        this.get({
            operation:'prev',
            effectDirection:'left'
        });
    }
    this.setQuestion = function(newQuestion){
        this.question = newQuestion;
    }
    this.addAnswers = function(answers){
        var _this = this;
        jQuery.each(answers, function(k,_answer){
            if(!_this.allAnswers[_answer.id])
                _this.allAnswers[_answer.id] = _answer;    
        })
    };
    this.getAnswerById = function(id){
        var res = null;

        if(this.allAnswers[id])
            res = this.allAnswers[id];
        return res;
    };
    //evento al contestar la pregunta
    this.onAnswer = function(answer_id){
        this.selectedAnswer = this.allAnswers[answer_id];
        //solo si no posee pregunta anterior generamos reply
        if(!this.prevQuestion){
            var _this = this;
            this.selectedAnswerId = answer_id;
            this.showExplication(this.allAnswers[answer_id]);
            //obtenemos reporte pie de respuestas
            this.get({
                operation:'reply',
                onSuccess:function(res){
                    var data = [];
                    var _answer = {};
                    if(res.report){
                        jQuery.each(res.report.answers, function(i,answer){
                            var q = 0;
                            jQuery.each(res.report.report, function(answerId,count){
                                if(answerId == answer.id){
                                    _answer = answer;
                                    q = count;
                                }
                            });
                            data.push({ answer:answer.description, population: q});
                            //this.store.loadData(data);
                            //solo si chart no existe lo creamos
                            if(_this.chart==null){
                                _this.createChart(data);
                            }
                            else{
                                _this.store.loadData(data);
                            }

                        });
                    }
                    var li = jQuery("#"+answer_id).parent();
                    li = li[0];
                    if(res.data.correct){
                        jQuery(li).css("background-color","#C6DEBA");
                    }   
                    else{
                        jQuery(li).css("background-color","#F2BDBD");
                    }
                }
            });
        }
        
    }
    this.getDOMQuestion = function(){
        var q = this.question;
        var ahtml = "";
        var select = "";
        if(q.type_questions_id == CFG.type_question_selection){
            ahtml = "<ul >";
            jQuery.each(q.answers, function(i,answer){
                ahtml = ahtml+"<li><input style='width:30px;float:left;' name='rname' id='"+answer.id+"' class='checkAnswer' type='radio'/><label>"+answer.description+"</label></li>";
            });
            ahtml = ahtml+"</ul>";
        }
        else{
            if(q.type_questions_id == CFG.type_question_pairterms){

                //creamos un select
                jQuery.each(q.innerAnswers,function(k,inner){
                    select = select + "<option>"+inner.description+"</option>";
                });
                select = "<select style='width:120px;float:left;height:30px;'>"+select+"</select>";


                ahtml = "<ul >";
                jQuery.each(q.answers, function(i,answer){
                    ahtml = ahtml + "<li><label style='width:150px;float:left;height:30px;'>"+answer.description+"</label>"+select+"</li>";
                    //ahtml = ahtml+"<li><input style='width:30px;float:left;' name='rname' id='"+answer.id+"' class='checkAnswer' type='radio'/><label>"+answer.description+"</label></li>";
                });
                ahtml = ahtml+"</ul>";
            }
        }
        if(!this.rendered){
            ahtml = '<ul class="exec_question">'+
                        '<li class="liQuestion">'+q.description+'</li>'+
                        '<li class="liAnswers">'+ahtml+'</li>'+
                    '</ul>';    
        }
        else{
            ahtml =     '<li class="liQuestion">'+q.description+'</li>'+
                        '<li class="liAnswers">'+ahtml+'</li>';
        }
        return ahtml;
    }
    //seteamos listeners
    this.afterRender = function(){
        //evento click sobre un radio button de answer
        var _this = this;
        jQuery("#"+this.renderTo+" .checkAnswer").on("click",function(){
            var id = jQuery(this).attr("id");
            _this.onAnswer(id);
        });

        //en el caso que presione el boton pregunta previa, cargamos la respuieswta seleccionada por le usuario
        if(this.prevQuestion){
            jQuery("#"+this.prevQuestion.execdetail.selected).attr('checked','checked');
            var li = jQuery("#"+this.prevQuestion.execdetail.selected).parent();
            li = li[0];
            if(this.prevQuestion.status == "OK"){
                jQuery(li).css("background-color","#C6DEBA");
            }
            else{
                jQuery(li).css("background-color","#F2BDBD");
            }
        }
        //en el caso que presione el boton pregunta previa, cargamos la respuieswta seleccionada por le usuario
        if(this.nextQuestion){
            jQuery("#"+this.nextQuestion.execdetail.selected).attr('checked','checked');
            var li = jQuery("#"+this.nextQuestion.execdetail.selected).parent();
            li = li[0];
            if(this.nextQuestion.status == "OK"){
                jQuery(li).css("background-color","#C6DEBA");
            }
            else{
                jQuery(li).css("background-color","#F2BDBD");
            }
        }
    }
    this.showExplication = function(answer){
        var _this = this;
        if(!this.winExplication){
            this.winExplication = new Ext.Window({
                title: 'Explicación',
                autoRender:false,
                resizable: false,
                width: 300,
                x:mouseX,
                y:mouseY,
                height: 150,
                forceFit: true,
                frame: false,
                layout: 'fit',
                modal: false,
                plain: true,
                buttonAlign: 'center',
                items: [
                    {
                        xtype:'textarea',
                        id:'txt_explication',
                        readOnly:true,
                        margin:'10'
                    }
                ],
                closable: true,
                buttons: [
                    {
                        text: 'Cerrar',
                        iconCls: 'x-icon-cancel',
                        handler: function() {
                            _this.winExplication.hide();
                        }
                    }
                ]
            });
            this.winExplication.on('close', function() {
                _this.winExplication.toggleCollapse();
            });
            this.winExplication.on('minimize', function() {
                _this.winExplication.toggleCollapse();
            });
        }
        


        this.winExplication.on('show',function(){
            Ext.getCmp('txt_explication').setValue(answer.explication);
        })

        if(answer.explication){
            this.winExplication.show();
            Ext.getCmp('txt_explication').setValue(answer.explication);    
        }
        
    };
    this.createChart = function(data){
        
        this.store = new Ext.data.JsonStore({
            fields: ['answer', 'population'],
            data: data   
        });
        this.chart = new Ext.chart.Chart( {
            width: 400,
            height: 300,
            animate: true,
            store: this.store,
            autoRender:false,
            renderTo: 'dChart',
            shadow: true,
            legend: {
                position: 'right'
            },
            insetPadding: 25,
            //theme: 'Base:gradients',
            series: [{
                type: 'pie',
                field: 'population',
                showInLegend: true,
                highlight: {
                  segment: {
                    margin: 20
                  }
                },
                label: {
                    field: 'answer',
                    display: 'rotate',
                    contrast: true,
                    font: '18px "Lucida Grande", "Lucida Sans Unicode", Verdana, Arial, Helvetica, sans-serif'
                },
                animate: true
            }]
        });
    }
    //render
    this.render = function(){
        var _this = this;
        var q = this.question;
        if(q === null){
            throw "(WidgetQuestion)->render: [question] must be initilized first";
            return false;
        }
        if(!this.renderTo){
            throw "(WidgetQuestion)->render: [renderTo] must be initilized first";
            return false;
        }
        if(!jQuery("#"+this.renderTo)){
            throw "(WidgetQuestion)->render: [renderTo] must be exist in DOM";
            return false;
        }

        if(!this.rendered){
            this.addAnswers(_this.question.answers);
            this.qhtml = this.getDOMQuestion(this.question);
            this.html = this.qhtml +
                    '<ul class="ul_inline question_controls" style="float:left;width:200px;margin:30px 0 0 43%;">'+
                        '<li style="width:40px;"><button id="prev" class="btn btn-success" title="Pregunta Previa"><i class="icon-step-backward"></i></button></li>'+
                        '<li style="width:40px;"><button id="next" class="btn btn-success" title="Pregunta Siguiente"><i class="icon-step-forward"></i></button></li>'+
                    '</ul>';
            jQuery("#"+this.renderTo).html(this.html);

            jQuery("#"+this.renderTo+" .question_controls #next").on("click",function(){
                _this.next();
            });
            jQuery("#"+this.renderTo+" .question_controls #prev").on("click",function(){
                _this.prev();
            });
        }
        else{
            var lis = jQuery("#"+this.renderTo+" .exec_question li");
            jQuery.each(lis,function(k,li){
                jQuery(li).remove();
            })
            //si ya existe solo cambiamos contenido y no todo el dom
            jQuery("#"+this.renderTo+" .exec_question").html(this.getDOMQuestion(this.question));
        }

        
        this.afterRender();
        this.rendered = true;
    }
}